<template>
  <div class="project-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">项目管理</span>
          <div class="right-button">
            <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="handleAdd">
              新增项目
            </el-button>
            <el-button type="info" :icon="useRenderIcon(Upload)" @click="handleImport">
              导入
            </el-button>
            <el-button type="warning" :icon="useRenderIcon(Download)" @click="handleExport">
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form ref="queryRef" :inline="true" :model="queryParams">
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目编码" prop="projectCode">
          <el-input
            v-model="queryParams.projectCode"
            placeholder="请输入项目编码"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in projectStatus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目日期" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="useRenderIcon(Search)" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="useRenderIcon(Refresh)" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="projectList" border style="width: 100%">
        <el-table-column prop="projectId" label="项目ID" align="center" width="100" />
        <el-table-column
          prop="projectName"
          label="项目名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="projectCode" label="项目编码" align="center" min-width="120" />
        <el-table-column prop="projectManager" label="项目负责人" align="center" min-width="120" />
        <el-table-column prop="status" label="项目状态" align="center" width="120">
          <template #default="scope">
            <el-tag :type="statusTagType(scope.row.status)">
              {{ statusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" align="center" width="120" />
        <el-table-column prop="endDate" label="结束日期" align="center" width="120" />
        <el-table-column prop="totalBudget" label="总预算" align="center" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.totalBudget) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalManMonths" label="总人月数" align="center" width="100" />
        <el-table-column prop="usedManMonths" label="已用人月数" align="center" width="100" />
        <el-table-column label="操作" align="center" width="240">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              :icon="useRenderIcon(EditPen)"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              :icon="useRenderIcon(View)"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-popconfirm
              :title="`是否确认删除项目'${scope.row.projectName}'?`"
              type="warning"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger" link :icon="useRenderIcon(Delete)"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @update:current-page="val => (queryParams.pageNum = val)"
        @update:page-size="val => (queryParams.pageSize = val)"
        class="pagination"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="projectForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目编码" prop="projectCode">
          <el-input v-model="form.projectCode" placeholder="请输入项目编码" />
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择项目状态">
            <el-option
              v-for="dict in projectStatus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectManager">
          <el-select
            v-model="form.managerId"
            placeholder="请选择项目负责人"
            style="width: 240px"
            @change="handleManagerChange"
          >
            <el-option
              v-for="item in personnelList"
              :key="item.personnelId"
              :label="item.personnelName"
              :value="item.personnelId"
            >
              <span>{{ item.personnelName }}</span>
              <span style="color: #8492a6; font-size: 13px"> ({{ item.personnelCode }}) </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目日期" prop="date">
          <el-date-picker
            v-model="projectDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="项目预算" prop="totalBudget">
          <el-input-number
            v-model="form.totalBudget"
            :min="0"
            :precision="2"
            :step="1000"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="总人月数" prop="totalManMonths">
          <el-input-number
            v-model="form.totalManMonths"
            :min="0"
            :precision="2"
            :step="0.5"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="已用人月数" prop="usedManMonths">
          <el-input-number
            v-model="form.usedManMonths"
            :min="0"
            :precision="2"
            :step="0.5"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="项目描述" prop="projectDesc">
          <el-input
            v-model="form.projectDesc"
            type="textarea"
            rows="4"
            placeholder="请输入项目描述"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog title="导入项目数据" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            <el-button type="primary" link @click="handleDownloadTemplate">下载模板</el-button>
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="upload.open = false">取 消</el-button>
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadInstance } from "element-plus";
import {
  getProjectList,
  getProjectDetail,
  addProject,
  updateProject,
  deleteProject as delProject,
  exportProject
} from "@/api/attendance/project";
import { ProjectVO, ProjectQuery, ProjectForm } from "@/types/attendance/project/index";
import { getPersonnelList } from "@/api/attendance/personnel";
import type { PersonnelVO } from "@/types/attendance/personnel";
import { UploadFilled } from "@element-plus/icons-vue";
import { handleApiError } from "@/utils/error-handler";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRouter } from "vue-router";
import { openTagByName } from "@/utils/tag-utils";

import AddFill from "@iconify-icons/ri/add-circle-line";
import Upload from "@iconify-icons/ep/upload";
import Download from "@iconify-icons/ep/download";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import View from "@iconify-icons/ep/document";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

// 项目状态常量
const projectStatus = [
  { value: "0", label: "规划中" },
  { value: "1", label: "进行中" },
  { value: "2", label: "已完成" },
  { value: "3", label: "已关闭" }
];

// 状态标签类型
const statusTagType = (status: string): "success" | "warning" | "info" | "danger" => {
  switch (status) {
    case "0":
      return "info";
    case "1":
      return "warning";
    case "2":
      return "success";
    case "3":
      return "danger";
    default:
      return "warning";
  }
};

// 状态标签展示
const statusLabel = (status: string) => {
  const dict = projectStatus.find(item => item.value === status);
  return dict ? dict.label : "";
};

// 金额格式化
const formatAmount = (amount: number | undefined) => {
  if (amount === undefined) return "-";
  return `¥${amount.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
};

// 查询参数
const queryParams = reactive<ProjectQuery>({
  projectName: "",
  projectCode: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});

// 日期范围
const dateRange = ref<[Date, Date] | null>(null);

// 表格数据
const projectList = ref<ProjectVO[]>([]);
const loading = ref(false);
const total = ref(0);

// 对话框属性
const dialog = reactive({
  title: "",
  visible: false
});

// 表单数据
const form = reactive<ProjectForm>({
  projectName: "",
  projectDesc: "",
  projectManager: "",
  projectCode: "",
  managerId: undefined,
  status: "0",
  startDate: "",
  endDate: "",
  totalBudget: 0,
  totalManMonths: 0,
  usedManMonths: 0,
  remark: ""
});

// 项目日期范围
const projectDateRange = ref<[Date, Date] | null>(null);

// 表单校验规则
const rules = reactive<FormRules>({
  projectName: [
    { required: true, message: "请输入项目名称", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "项目名称长度在2到100个字符之间",
      trigger: "blur"
    }
  ],
  projectCode: [
    { required: true, message: "请输入项目编码", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "项目编码长度在2到50个字符之间",
      trigger: "blur"
    }
  ],
  status: [{ required: true, message: "请选择项目状态", trigger: "change" }],
  projectManager: [{ required: false, message: "请输入项目负责人", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }]
});

// 上传相关
const upload = reactive({
  open: false,
  url: "/project/import",
  headers: { Authorization: "Bearer " + localStorage.getItem("token") },
  isUploading: false
});

// 表单引用
const queryRef = ref<FormInstance>();
const projectForm = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();

// 人员列表
const personnelList = ref<PersonnelVO[]>([]);

// 获取人员列表
const getPersonnelOptions = async () => {
  try {
    const res = await getPersonnelList({
      pageNum: 1,
      pageSize: 1000,
      status: "0" // 只获取在岗人员（0在岗 1离场 2休假）
    });
    console.log("人员列表数据:", res.data); // 添加日志
    personnelList.value = res.data.rows || [];
  } catch (error) {
    handleApiError(error);
  }
};

// 获取项目列表
const getList = async () => {
  loading.value = true;
  try {
    // 创建新的查询参数对象，避免修改原始对象
    const params = { ...queryParams };

    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      // 将日期转换为字符串格式 yyyy-MM-dd
      const startDateStr = dateRange.value[0].toISOString().split("T")[0];
      const endDateStr = dateRange.value[1].toISOString().split("T")[0];

      // 设置查询参数，项目的起始和结束日期必须在用户选择的日期范围内
      params.beginStartDate = startDateStr; // 项目开始日期 >= 选择的开始日期
      params.endEndDate = endDateStr; // 项目结束日期 <= 选择的结束日期

      console.log("日期查询参数:", {
        beginStartDate: params.beginStartDate,
        endEndDate: params.endEndDate
      });
    }

    const res = await getProjectList(params);
    projectList.value = res.data.rows || [];
    total.value = res.data.total || 0;
  } catch (error) {
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  dateRange.value = null;
  handleQuery();
};

// 分页操作
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getList();
};

// 页码操作
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getList();
};

// 新增按钮操作
const handleAdd = () => {
  dialog.title = "添加项目";
  dialog.visible = true;
  projectDateRange.value = null;
  resetForm();
};

// 编辑按钮操作
const handleUpdate = async (row: ProjectVO) => {
  dialog.title = "修改项目";
  dialog.visible = true;
  resetForm();

  try {
    const res = await getProjectDetail(row.projectId as number);
    Object.assign(form, res.data);
    // 设置日期范围
    if (form.startDate && form.endDate) {
      projectDateRange.value = [new Date(form.startDate), new Date(form.endDate)];
    }
  } catch (error) {
    handleApiError(error);
  }
};

// 查看按钮操作
const handleView = async (row: ProjectVO) => {
  openTagByName(
    router,
    "AttendanceProjectDetail",
    `项目详情-${row.projectName}`,
    { id: row.projectId },
    {
      activeMenu: "/attendance/project",
      dynamicLevel: 3
    }
  );
};

// 删除按钮操作
const handleDelete = async (row: ProjectVO) => {
  try {
    await delProject(row.projectId as number);
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    handleApiError(error);
  }
};

// 导出按钮操作
const handleExport = () => {
  // 处理日期范围
  const params = { ...queryParams };
  if (dateRange.value && dateRange.value.length === 2) {
    // 将日期转换为字符串格式 yyyy-MM-dd
    const startDateStr = dateRange.value[0].toISOString().split("T")[0];
    const endDateStr = dateRange.value[1].toISOString().split("T")[0];

    // 设置查询参数，项目的起始和结束日期必须在用户选择的日期范围内
    params.beginStartDate = startDateStr; // 项目开始日期 >= 选择的开始日期
    params.endEndDate = endDateStr; // 项目结束日期 <= 选择的结束日期
  }

  exportProject(params);
};

// 导入按钮操作
const handleImport = () => {
  upload.open = true;
};

// 下载导入模板
const handleDownloadTemplate = () => {
  // 下载模板函数
};

// 文件上传中
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

// 文件上传成功
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }

  ElMessage.success(response.msg || "导入成功");
  getList();
};

// 提交上传文件
const submitFileForm = () => {
  if (uploadRef.value) {
    uploadRef.value.submit();
  }
};

// 重置表单
const resetForm = () => {
  form.projectId = undefined;
  form.projectName = "";
  form.projectDesc = "";
  form.projectManager = "";
  form.projectCode = "";
  form.managerId = undefined;
  form.status = "0";
  form.startDate = "";
  form.endDate = "";
  form.totalBudget = 0;
  form.totalManMonths = 0;
  form.usedManMonths = 0;
  form.remark = "";

  if (projectForm.value) {
    projectForm.value.resetFields();
  }
};

// 提交表单
const submitForm = async () => {
  if (!projectForm.value) return;

  await projectForm.value.validate(async valid => {
    if (!valid) return;

    // 处理日期
    if (projectDateRange.value) {
      form.startDate = projectDateRange.value[0];
      form.endDate = projectDateRange.value[1];
    }

    try {
      if (form.projectId) {
        // 更新
        await updateProject(form);
        ElMessage.success("修改成功");
      } else {
        // 新增
        await addProject(form);
        ElMessage.success("新增成功");
      }
      dialog.visible = false;
      getList();
    } catch (error) {
      // 使用通用的错误处理替代项目特定的错误处理
      ElMessage.error("操作失败");
      handleApiError(error);
    }
  });
};

// 处理项目负责人选择变化
const handleManagerChange = (personnelId: number) => {
  console.log("选择的人员ID:", personnelId); // 添加日志
  const selectedPerson = personnelList.value.find(p => p.personnelId === personnelId);
  if (selectedPerson) {
    form.projectManager = selectedPerson.personnelName;
    console.log("选中的人员信息:", selectedPerson); // 添加日志
  }
};

// 初始化
const router = useRouter();
onMounted(() => {
  getList();
  getPersonnelOptions();
});
</script>

<style lang="scss" scoped>
.project-container {
  padding: 10px;

  .box-card {
    width: 100%;
    margin-bottom: 10px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: bold;
    }

    .right-button {
      display: flex;
      gap: 8px;
    }
  }

  :deep(.el-form) {
    margin-bottom: 15px;

    .el-form-item {
      margin-bottom: 15px;
      margin-right: 10px;
    }
  }

  :deep(.el-table) {
    margin: 15px 0;
  }

  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
